package com.lczc.soa.filter;

import com.lczc.soa.utils.SensitiveWordUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;


@WebFilter(urlPatterns = {"/*"}, filterName = "sensitiveWordsFilter")
public class SensitiveWordsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("\n-------- SensitiveWordsFilter.init --- ");
        System.out.println("getFilterName:"+filterConfig.getFilterName());
        System.out.println("getServletContext:"+filterConfig.getServletContext());
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        //获取前端传递的所有参数名的枚举
        Enumeration enumeration = request.getParameterNames();
        //遍历枚举
        while(enumeration.hasMoreElements()){
            //获取参数名
            String name=(String)enumeration.nextElement();
            //获取参数值
            String value =request.getParameter(name);
            //对参数值进行敏感词处理,并重新设置到request
            String str = SensitiveWordUtil.sensitiveHelper(value);
            if(str.equals(value)){
                System.out.println("\n-------- SensitiveWordsFilter.do --- ");
                System.out.println("no sensitive words:"+value);
                request.setAttribute(name,value);
            }else{
                //request.removeAttribute(name);
                System.out.println("\n-------- SensitiveWordsFilter.do --- ");
                System.out.println("replace:"+value+"=========>"+str);
                request.setAttribute(name,str);
            }
        }
        //放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("\n-------- SensitiveWordsFilter.destroy --- ");
    }
}
